package cn.schoolwow.quickdao.module.database.dml.instance.flow.insert.common;

import cn.schoolwow.quickdao.domain.entity.Property;
import cn.schoolwow.quickdao.module.database.dml.instance.flow.insert.get.GetSinglePropertyValueListFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.instance.QueryInstance;

import java.util.List;
import java.util.Set;

public class DistinguishBySinglePropertyFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        Object[] instances = (Object[]) flowContext.checkData("instances");
        Property singleProperty = flowContext.checkData("singleProperty", Property.class);
        Set<Object> existInstanceSet = flowContext.getData("existInstanceSet", Set.class);

        flowContext.startFlow(new GetSinglePropertyValueListFlow())
                .putTemporaryData("singleProperty", singleProperty)
                .execute();
        List<String> singlePropertyValueList = (List<String>) flowContext.getData("singlePropertyValueList");
        if(singlePropertyValueList.isEmpty()){
            return;
        }

        for(int i=0;i<instances.length;i++){
            Object instance = instances[i];

            Object singlePropertyValue = QueryInstance.newQuery(instance)
                    .execute()
                    .getSingleFieldValue(singleProperty.name);
            if(null==singlePropertyValue){
                throw new IllegalArgumentException("实例指定字段不能为空!实体类:"+instance.getClass().getName()+",字段名:"+singleProperty.name);
            }
            if(singlePropertyValueList.contains(singlePropertyValue.toString())){
                existInstanceSet.add(instance);
            }
        }
    }

    @Override
    public String name() {
        return "根据单个字段判断实例是否存在";
    }
}
